#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll P = 20130427, maxn = 1e5+10;
ll L[maxn], R[maxn], B, N, M, *A, f[maxn], pw[maxn], MO[maxn];

inline void up(ll& a, ll b){a = (a+b)%P;}

ll dp(int p, int l, bool lim){
    if(p<0 || !l)
        return 0;
    if(!lim)
        return f[l];
    int m = A[p];
    ll ans = 0;
    for (int i = 0; i <= m; ++i) {
        for (int j = 1; j <= l ; ++j) {
            up(ans, i*pw[j-1] + dp(p-1, j-1, i == m));
        }
    }
    return ans;
}


int main() {
    ios::sync_with_stdio(false);cin.tie(nullptr);
    cin >> B;
    pw[0] = 1;
    cin >> N;
    for (ll i = N-1; i >=0; --i) {
        cin >> L[i];
    }
    cin >> M;
    for (ll i = M-1; i >=0; --i) {
        cin >> R[i];
    }
    for (int i = 0; i < N; ++i) {
        if(L[i]) {L[i]--; break;}
        else {
            L[i] = B-1;
            if(i == N-1) N--;
        }
    }

    for (int i = 1; i <= max(N, M); ++i) {
        pw[i] = pw[i-1]*B%P;
        for (int n = 1; n < B; ++n) {
            for (int l = 1; l <= i; ++l) {
                up(f[i], n*pw[l-1]);
            }
        }
        up(f[i], f[i-1]);
    }

    A = R;
    ll ansr = dp(M-1, M, true);
    A = L;
    ll ansl = dp(N-1, N, true);
    cout << ansr - ansl;
    return 0;
}
/**
10
1 1
2 1 0
**/

/***
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll P = 20130427, maxn = 1e5+10;
ll L[maxn], R[maxn], B, N, M, *A, f[maxn], pw[maxn];

inline void up(ll& a, ll b){a = (a+b)%P;}

ll dp(int p, int l, bool lim, bool z){
    if(p<0 || !l)
        return 0;
    if(!lim && !z)
        return f[l];
    int m = lim?A[p]:B-1;
    ll ans = 0;
    for (int i = 0; i <= m; ++i) {
        if(i==0 && z)
            up(ans, dp(p-1, l-1, lim&&i==m, true));
        else{
            for (int j = 1; j <= l ; ++j) {
                up(ans, i*pw[j-1] + dp(p-1, j-1, lim&&i==m, false));
            }
        }
    }
    return ans;
}


int main() {
    ios::sync_with_stdio(false);cin.tie(nullptr);
    cin >> B;
    pw[0] = 1;
    cin >> N;
    for (ll i = N-1; i >=0; --i) {
        cin >> L[i];
    }
    cin >> M;
    for (ll i = M-1; i >=0; --i) {
        cin >> R[i];
    }
    for (int i = 0; i < N; ++i) {
        if(L[i]) {L[i]--; break;}
        else {
            L[i] = B-1;
            if(i == N-1) N--;
        }
    }

    for (int i = 1; i <= max(N, M); ++i) {
        pw[i] = pw[i-1]*B%P;
        for (int n = 1; n < B; ++n) {
            for (int l = 1; l <= i; ++l) {
                up(f[i], n*pw[l-1]);
            }
        }
        up(f[i], f[i-1]);
    }

    A = R;
    ll ansr = dp(M-1, M, true, true);
    A = L;
    ll ansl = dp(N-1, N, true, true);
    cout << ansr - ansl;
    return 0;
}
***/